﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;
using SuppKids.Licensing.Common;
using SuppKids.Licensing.LicenseManager.Utilities.RSA;

namespace SuppKids.Licensing.LicenseManager
{
	public class LicenseManagementService
	{
		private readonly RSACryptoTransformer rsaCryptoTransformer;

		public LicenseManagementService(RSACryptoTransformer rsaCryptoTransformer)
		{
			this.rsaCryptoTransformer = rsaCryptoTransformer;
		}

        public virtual string GenerateAndSignXmlLicense(LicenseDTO licenseDTO)
		{
            var license = this.GenerateXmlLicense(licenseDTO);

			this.rsaCryptoTransformer.Sign(license);
			return license.OuterXml;
		}

        private XmlDocument GenerateXmlLicense(LicenseDTO licenseDTO)
		{
			var xmlSerializer = new XmlSerializer(typeof(LicenseDTO));
			using (var stream = new MemoryStream())
			{
                xmlSerializer.Serialize(stream, licenseDTO);
				using (var reader = new StreamReader(stream))
				{
					stream.Seek(0, SeekOrigin.Begin);
					var licenseXml = reader.ReadToEnd();

					var result = new XmlDocument();
					result.LoadXml(licenseXml);

					if (result.DocumentElement == null)
					{
						return new XmlDocument();
					}

					return result;
				}
			}
		}

		
	}
}
